"""HTTP-specific events."""
import json

import mitmproxy.http
from mitmproxy import ctx


# mitmproxy的http事件
class Events:

    def response(self, flow: mitmproxy.http.HTTPFlow):
        """
            The full HTTP response has been read.
            https://stock.xueqiu.com/v5/stock/percent/batch/target.json?_t=1NETEASE9a661ca530a903f315d414b1755ff231.1705060227.1627916928559.1
            627917013694&_s=d837e7&x=0.393&symbols=SH688981%2CSZ000762%2CSZ300343%2CSZ000661%2CSZ002507%2CSH600196%2CSZ300693%2CSZ002594%2CSH600519%2CSZ300827%2CSH6005
            18%2CSH600036%2CSH600000
        """
        # 判断是否“响应内容为雪球->行情->股票”的请求，以获取“雪球->行情->股票”的响应内容
        if "quote.json" in flow.request.pretty_url and "x=" in flow.request.pretty_url:
            # 获取http响应内容并转换成一个json格式的python对象
            data_response = json.loads(flow.response.content)
            # 将响应内容转换成字符串格式输出到日志
            ctx.log.info(str(data_response))
            # 将http响应内容以json格式写入文件response_data.json,方便查看结构层次
            with open("./mitm_practice/response_data.json", "w", encoding="utf-8") as f:
                f.write(str(data_response))
            # 修改雪球服务器返回的响应内容，修改第1支股票名称，以及第1支直到第6支股票的涨跌幅，以观察股票颜色变化的边界值
            data_response["data"]["items"][0]["quote"]["name"] = "中芯国际kkkkkkk巴拉拉巴拉附加费JFJFjjjj"
            data_response["data"]["items"][0]["quote"]["percent"] = 0.00
            data_response["data"]["items"][1]["quote"]["percent"] = +17.34
            data_response["data"]["items"][2]["quote"]["percent"] = +120.00
            data_response["data"]["items"][3]["quote"]["percent"] = -0.01
            data_response["data"]["items"][4]["quote"]["percent"] = -12.78
            data_response["data"]["items"][5]["quote"]["percent"] = -150.00
            # 将修改后的响应内容序列化为json格式字符串，并赋值给mitmproxy的http响应，以返回给客户端
            flow.response.text = json.dumps(data_response)


# addons是一个插件，是一个列表，所有的实例都放在addons里面实现
addons = [
    Events()
]
